package com.meshnetics.gb.stack.core.apl.type;

import com.meshnetics.gb.type.impl.zcl.FixedBytesDataValue;

/**
 * Realization of ByteableNumber for cluster Id (u-int-16).
 *
 * @author Yury Aserchev (yaserchev@meshnetics.com)
 *         Date: 08.07.2008 14:28:40
 * @author mmarkov
 */
public class ClusterId extends FixedBytesDataValue {
    /** Minimum allowed cluster id. */
    public static final int MIN_ID = 0;

    /** Maximum allowed cluster id. */
    public static final int MAX_ID = 65535;

    /**
     * Constructs ClusterId from the given int value.
     *
     * @param id int cluster id
     * @throws IllegalArgumentException if the given id is < 0 or > 65535
     */
    public ClusterId(int id) {
        super(TypeClusterId.TYPE, new byte[] { (byte) (id >> 8), (byte) id });

        if ((id < MIN_ID) || (id > MAX_ID)) {
            throw new IllegalArgumentException("Invalid cluster id: " + id);
        }
    }

    /**
     * Constructs ClusterId from the array of bytes (which should contain 2 elements).
     * It's needed for its constructing from TypeClusterId.createValue() method.
     *
     * @param type TypeClusterId
     * @param value byte array with 2 elements
     */
    protected ClusterId(TypeClusterId type, byte[] value) {
        super(type, value);
    }

    /**
     * Returns true as ClusterId is effectively uint-16.
     *
     * @return true
     */
    protected boolean isUnsigned() {
        return true;
    }

    /**
     * Returns false as there's no limitation for ClusterId within 2-bytes range.
     *
     * @return false
     */
    public boolean isInvalid() {
        return false;
    }

    /**
     * Returns id value as int.
     *
     * @return id value as int.
     */
    public int getIntId(){
        return ((value[0] & 0xFF) << 8) + (value[1] & 0xFF);
    }
}
